import { defineStore } from 'pinia'
import type { Product, Category } from '@/types/product'

interface ProductState {
  products: Product[]
  categories: Category[]
  totalProducts: number
  loading: boolean
}

export const useProductStore = defineStore('product', {
  state: (): ProductState => ({
    products: [],
    categories: [
      { id: 1, name: '电子产品' },
      { id: 2, name: '服装' },
      { id: 3, name: '图书' },
      { id: 4, name: '生活用品' }
    ],
    totalProducts: 0,
    loading: false
  }),
  
  getters: {
    getProductById: (state) => {
      return (id: number) => state.products.find(p => p.id === id)
    },
    getCategoryById: (state) => {
      return (id: number) => state.categories.find(c => c.id === id)
    }
  },

  actions: {
    setProducts(products: Product[]) {
      this.products = products
      this.totalProducts = products.length
    },

    updateProduct(product: Product) {
      const index = this.products.findIndex(p => p.id === product.id)
      if (index > -1) {
        this.products[index] = product
      }
    },

    deleteProduct(id: number) {
      this.products = this.products.filter(p => p.id !== id)
      this.totalProducts = this.products.length
    },

    setLoading(status: boolean) {
      this.loading = status
    },

    addCategory(category: Category) {
      this.categories.push(category)
    },

    updateCategory(category: Category) {
      const index = this.categories.findIndex(c => c.id === category.id)
      if (index > -1) {
        this.categories[index] = category
      }
    },

    deleteCategory(id: number) {
      this.categories = this.categories.filter(c => c.id !== id)
    }
  }
}) 